#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:pengfeifu
@file: day_17_mysql.py.py 
@version:
@time: 2021/11/05 
@email:1324734112@qq.com
@desc： 链接mysql
@function：常用函数
1.cursor()创建游标对象
2.execute()执行sql语句
3.fetchall()取出数据
4.rollback()异常发生回滚
5.commit()事务提交
注意:
   mysql.connector与pymysql性能不高，python3经常使用mysqldb作为线上生产用
"""

import mysql.connector
import pymysql
import MySQLdb


def py_mysql_connect(sql):
    # 创建mysql数据库链接
    try:
        db = pymysql.connect(
            host="192.168.142.130",
            user="root",
            port=3306,
            passwd="root@123",
            database="member",
            charset="utf8"
        )
        # 创建游标对象
        cursor = db.cursor()
        # 通过execute()方法执行查询sql
        cursor.execute(sql)
        # 通过fetchall()方法获取所有数据
        data = cursor.fetchall()
    except Exception:
        print("数据库链接失败")
    finally:
        db.close()  # 关闭链接
    return data


# 调用mysql.connection组件
def mysql_python_connect(sql):
    try:
        db = mysql.connector.connect(
            host="192.168.142.130",
            user="root",
            passwd="root@123",
            database="member"
        )
        # 创建游标对象
        cursor = db.cursor()
        # 通过execute()方法执行查询sql
        cursor.execute(sql)
        # 通过fetchall()方法获取所有数据
        data = cursor.fetchall()
    except Exception:
        print("数据库链接失败")
    finally:
        # 关闭链接
        db.close()
    return data


def mysql_db_connect(sql):
    try:
        db = MySQLdb.connect(
            host="192.168.142.130",
            port=3306,
            user="root",
            passwd="root@123",
            database="member",
            charset="utf8"
        )
        # 创建游标对象
        cursor = db.cursor()
        # 通过execute()方法执行查询sql
        cursor.execute(sql)
        # 通过fetchall()方法获取所有数据
        data = cursor.fetchone()
    except Exception:
        print("数据库链接失败")
    finally:
        cursor.close()
        # 关闭链接
        db.close()
    return data


if __name__ == "__main__":
    result = mysql_db_connect("select count(1) from wx_message")
    print(result)
